package junior.db.dao.query;

import junior.db.dao.base.IExecuteAware;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wubo
 * @date 2025/5/20 15:24
 */
@Getter
public class WithQuery extends AbstractQuery<WithQuery> implements IExecuteAware {
    private List<WithQueryNode> nodeList = new ArrayList<>();
    private String fromCte;
    private boolean recursive;
    
    public <Q extends AbstractQuery<?>> WithQuery(Q query, String cte) {
        this.fromCte = cte;
        nodeList.add(new WithQueryNode(query, cte));
    }
    
    public <Q extends AbstractQuery<?>> WithQuery withCte(Q query, String cte) {
        nodeList.add(new WithQueryNode(query, cte));
        return this;
    }
    
    public WithQuery withRecursive() {
        this.recursive = true;
        return this;
    }
    
    public WithQuery from(String cte) {
        this.fromCte = cte;
        return this;
    }
    
    @Override
    public String getTable() {
        return fromCte;
    }
    
    @Override
    public List<ISelectItem> getFinalSelectFields() {
        if (super.isSelectAll()) {
            return List.of(new SelectExpression("*", null));
        }
        return super.getFinalSelectFields();
    }
    
    @Override
    public void beforeExecute() {
        super.beforeExecute();
        if (nodeList != null) {
            for (WithQueryNode q : nodeList) {
                q.getQuery().beforeExecute();
            }
        }
    }
    
    @AllArgsConstructor
    @Getter
    public static class WithQueryNode {
        private AbstractQuery<?> query;
        private String cte;
    }
}
